import {Router, ActivatedRoute} from '@angular/router';
import {Component, ViewEncapsulation, ChangeDetectorRef, OnDestroy} from '@angular/core';

import PhotoSwipe from 'photoswipe';
import * as PhotoSwipeUI_Default from 'photoswipe/dist/photoswipe-ui-default.js';
import {Location} from '@angular/common';

import {Subject} from "rxjs";
import {ToolsService} from "@shared/service/tools/tools.service";
import {NewsService} from "@news/news.service";
import {ArticleVO, RecommendArticleVO} from "@interface/index";
import {SeoService} from "@core/seo/seo.service";


@Component({
  selector: 'photo-news',
  templateUrl: './photo-news.component.html',
  styleUrls: ['./photo-news.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class PhotoNewsComponent implements OnDestroy {
  public news: Array<ArticleVO | any>;
  public recommendNews: Array<RecommendArticleVO>;
  public newsInfo: ArticleVO;
  public fade = false;
  public currentIndex = 0;
  public ngUnsubscribe: Subject<void> = new Subject<void>();

  constructor(public tools: ToolsService,
              public route: ActivatedRoute,
              public router: Router,
              public newService: NewsService,
              public _location: Location,
              public cdRef: ChangeDetectorRef,
              public _seoService: SeoService) {
    this.route.params.subscribe(params => {
      const cateId = params['cateId'], articleId = params['articleId'];
      this.getRecommendNews(cateId, articleId);
    });


  }

  /**
   * 获取推荐图集
   * @param cateId 资讯类型ID
   */
  getRecommendNews(cateId: number, articleId: number) {
    this.newService.getRecommendPhotoNews(cateId, articleId)
      .takeUntil(this.ngUnsubscribe)
      .subscribe(res => {
        if (res.result === '0') {
          this.recommendNews = res.data;
          this.getNewsBasicInfo(articleId);
        }
      });
  }

  /**
   * 资讯基本信息
   * @param articleId 资讯id
   */
  getNewsBasicInfo(articleId) {
    this.newService.GetCateArticleInfo(articleId)
      .takeUntil(this.ngUnsubscribe)
      .subscribe(res => {
        if (res.result === '0') {
          const newsInfo = res.data;
          this.newsInfo = newsInfo;
          this.getNews(articleId, res.data.contentSize);
          this._seoService.setTKD(
            `${newsInfo.title}_体育资讯`,
            `${newsInfo.title}_${newsInfo.cateName}`,
            `求苗体育聚集各类体育产业IP，包含但不限于体育赛事、体育培训、体育旅游、体育赞助、体育用品等各大板块，
      实现多种资源的聚合与互通, 赛事运营管理、合作机构对接、消费数据统计及线上推广等多服务轻松一键搞定的健康运动服务的互联网平台`
          );
        }
      });
  }

  /**
   * 获取图集
   * @param articleId 图集ID
   */
  getNews(articleId: number, rows: number) {
    this.newService.getPhotoNews(articleId, rows)
      .takeUntil(this.ngUnsubscribe)
      .subscribe(res => {
        if (res.result === '0') {
          let newsArr = this.news = res.data.list;
          this.reSize(newsArr);
        }
      });
  }

  /**
   * 设置图片尺寸
   * @param newsArr 组图数组
   */
  reSize(newsArr) {
    const that = this;
    const photos = [];
    let photo;
    this.tools.showLoading();

    for (const news of newsArr) {
      const img = new Image();
      let w;
      let h;
      // 设置图片宽高
      img.onload = function () {
        w = img.width;
        h = img.height;
        photo = {
          src: news['imgUrl'],
          w: w,
          h: h,
          mark: news['seq']
        };
        photos.push(photo);
        // 按顺序升序
        photos.sort(function (a, b) {
          const aM = a['mark'];
          const bM = b['mark'];
          return aM - bM;
        });

        if (photos.length !== newsArr.length) {
          return;
        }
        ;
        //   // 若有推荐组图
        if (that.recommendNews.length > 0) {
          photos.push({
            html: ''
          });
        }
        that.initGallery(photos);
      };
      img.src = news['imgUrl'];
    }

  }

  goToComment() {
    this.router.navigate(['news/comment', this.newsInfo.articleId]);
  }

  /**
   * 初始化
   */
  initGallery(newsArr) {
    if (newsArr.length > 0) {
      let options = {
        spacing: 0, // 间隔
        loop: false,
        preventHide: true,
        allowUserZoom: false,
        captionAndToolbarShowEmptyCaptions: false,
        preventSlideshow: true,
        zIndex: '10',
        escKey: false,
        closeOnVerticalDrag: false,
        imageScaleMethod: 'zoom',
        arrowKeys: false,
        //  captionAndToolbarAutoHideDelay: 3333,
        history: false,
        showAnimationDuration: 0,
        hideAnimationDuration: 0,
        errorMsg: '<div class="pswp__error-msg"><a href="%url%" target="_blank">此图片</a>无法加载~</div>'
      };

      const that = this;
      const galleryContainer: any = document.querySelector('.pswp');
      const gallery = new PhotoSwipe(galleryContainer, PhotoSwipeUI_Default, newsArr, options);
      this.tools.hideLoading();
      gallery.listen('afterChange', function () {
        const currentIndex = that.currentIndex = gallery.getCurrentIndex();
        that.cdRef.detectChanges(); // 更新視圖
        if (currentIndex === newsArr.length - 1 && that.recommendNews.length > 0) {
          document.getElementById('recommendEntry').click(); // 模拟点击事件
        }
        let introduce = document.querySelector('.introduce .content');
        if (introduce && introduce.scrollTop > 0) {
          introduce.scrollTop = 0;
        }

      });
      gallery.init();

      gallery.framework.bind(gallery['scrollWrap'], 'pswpTap', function (e) {
        that.fade = !that.fade;
        that.cdRef.detectChanges(); // 更新視圖
      });
    }
  }

  /**
   * 前往推荐组图
   */
  goToRecommendNew() {
    this.router.navigate(['news/recommend', this.newsInfo.cateId, this.newsInfo.articleId]);
  }

  ngOnDestroy() {
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();
  }
}
